package com.jingdianjichi.project.application.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName:FeignRequestInterceptor
 * Package:com.jingdianjichi.subject.application.interceptor
 * Description:
 *
 * @Author fst
 * @Create 2025/1/4 19:57
 * @Version 1.0
 */

@Component
public class FeignRequestInterceptor  implements RequestInterceptor
{
    @Override
    public void apply(RequestTemplate requestTemplate)
    {
        // 获取当前请求的 ServletRequestAttributes
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes!= null) {
            // 获取 HttpServletRequest
            HttpServletRequest request = attributes.getRequest();
            if (request!= null) {
                // 从请求头中获取用户 ID，假设用户 ID 的请求头名为 "userId"
                String loginId = request.getHeader("loginId");
                if (loginId!= null &&!loginId.isEmpty()) {
                    // 将用户 ID 添加到 Feign 请求的请求头中
                    requestTemplate.header("loginId", loginId);
                }
            }
        }
    }
}
